﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ThuVien;
using System.Data;
using System.IO;
//using ComponentArt.Web.UI;

namespace TranTekBE
{
    public partial class ProductDetails : PageRequireLogin
    {
        public int ProductISN
        {
            get
            {
                return FunctionsUtils.GetValueIntFromQueryString("isn", 0);
            }
        }

        public int MultiViewProductIndex
        {
            get
            {
                return FunctionsUtils.GetValueIntFromQueryString("idx", 0);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Hook the Save event to the Editor
            ///Editor1.Save += new Editor.SaveEventHandler(Editor1_Save);

            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadJS", "LoadJS();", true);

            if (this.Page.IsPostBack == false)
            {
                this.GetProductName(this.ProductISN);
                this.LoadViewIndex(this.MultiViewProductIndex);
                //this.GetProductInfoByISN(this.ProductISN);
            }
        }

        private void LoadViewIndex(int index)
        {
            ltUpdateSuccess.Text = string.Empty;
            lbtProductInfo.CssClass = string.Empty;
            lbtPictures.CssClass = string.Empty;
            lbtSpecifications.CssClass = string.Empty;
            switch (index)
            {
                case 1: //view pictures
                    lbtPictures.CssClass = "selected";
                    this.GetImagesOfProduct(this.ProductISN);
                    break;
                case 2: //view specification
                    lbtSpecifications.CssClass = "selected";
                    this.GetProductSpecification(this.ProductISN);
                    break;
                default: //view ProductInfo
                    lbtProductInfo.CssClass = "selected";
                    this.Page.Form.DefaultButton = btnSubmit.UniqueID;
                    index = 0;
                    this.GetProductInfoByISN(this.ProductISN);
                    break;
            }
            mvProduct.ActiveViewIndex = index;
        }

        private void GetProductName(int productISN)
        {
            try
            {
                DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select * From Vw_Product Where ProductISN = " + productISN.ToString());
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    ltProductName.Text = FunctionsUtils.HTMLEncode(ds.Tables[0].Rows[0]["proName"]);
                }
                else
                {
                    ltError.Text = string.Format(FunctionsUtils.Msg["frm_NotExist"], "Product");
                }
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (GetProductName): {0} {1}", ex, ex.StackTrace);
            }
        }

        private void GetProductSpecification(int productISN)
        {
            try
            {
                DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select * From Vw_Product Where ProductISN = " + productISN.ToString());
                //Editor1.ContentHTML = FunctionsUtils.ConvertToString(ds.Tables[0].Rows[0]["proDesc"], string.Empty);
                txtEditor.Text = FunctionsUtils.ConvertToString(ds.Tables[0].Rows[0]["proDesc"], string.Empty);
            }
            catch (Exception ex)
            {
                ltSpecificationError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (GetProductSpecification): {0} {1}", ex, ex.StackTrace);
            }
        }

        private void GetProductInfoByISN(int productISN)
        {
            try
            {
                DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select * From Vw_Product Where ProductISN = " + productISN.ToString());
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    //ltProductName.Text = FunctionsUtils.HTMLEncode(ds.Tables[0].Rows[0]["proName"]);

                    txtProductName.Text = ds.Tables[0].Rows[0]["proName"].ToString();
                    FunctionsUtils.SelectItemInControlList(rblStatus, ds.Tables[0].Rows[0]["proStatus"].ToString(), SelectBy.Value);
                    txtPrice.Text = FunctionsUtils.Format(ds.Tables[0].Rows[0]["proPrice"], FunctionsUtils.GetConfigValue("NumberFormat"));
                    txtOnhandQty.Text = ds.Tables[0].Rows[0]["proOnhandQty"].ToString();
                    txtComments.Text = ds.Tables[0].Rows[0]["proComment"].ToString();

                    this.GetCategoryForListBox(ds.Tables[0].Rows[0]["CategoryISNs"].ToString());                    
                }
                else
                {
                    ltError.Text = string.Format(FunctionsUtils.Msg["frm_NotExist"], "Product");
                }
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail ()GetProductInfoByISN: {0} {1}", ex, ex.StackTrace);
            }
        }

        private void GetCategoryForListBox(string lstRightCategoryISNs)
        {
            //left listbox
            try
            {
                string sql = string.Empty;
                
                sql = "Select CategoryISN, catName From Category";
                if (lstRightCategoryISNs.Length > 0)
                {
                    lstRightCategoryISNs = lstRightCategoryISNs.Replace(";", ",");
                    string sqlRight = string.Format("{0} Where CategoryISN In ({1})", sql, lstRightCategoryISNs);
                    FunctionsUtils.BindDataForControlList(lbCategoryRight, FunctionsUtils.Database.ExecuteQuery(sqlRight), "CategoryISN", "catName");

                    sql = string.Format("{0} Where CategoryISN Not In ({1})", sql, lstRightCategoryISNs);
                }
                FunctionsUtils.BindDataForControlList(lbCategoryLeft, FunctionsUtils.Database.ExecuteQuery(sql), "CategoryISN", "catName");
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (GetCategoryForListBox): {0} {1}", ex, ex.StackTrace);
            }
        }

        protected void ControlClick_Command(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "ProductInfo":
                    //mvProduct.ActiveViewIndex = 0;
                    this.LoadViewIndex(0);
                    break;
                case "Pictures":
                    //mvProduct.ActiveViewIndex = 1;
                    this.LoadViewIndex(1);
                    break;
                case "Specifications":
                    //mvProduct.ActiveViewIndex = 2;
                    this.LoadViewIndex(2);
                    //Response.Redirect(string.Format("ProductDetails.aspx?isn={0}&idx={1}", this.ProductISN, 2, true));
                    break;
                case "SaveProductInfo":
                    if (this.CheckData() == true)
                    {
                        this.SaveProduct(this.ProductISN, txtProductName.Text.Trim(), FunctionsUtils.ConvertToInt(rblStatus.SelectedValue, 0), FunctionsUtils.ConvertToDecimal(txtPrice.Text.Trim(), 0), FunctionsUtils.ConvertToDecimal(txtOnhandQty.Text.Trim(), 0), FunctionsUtils.ConvertFromListBoxToStringList(lbCategoryRight), txtComments.Text.Trim(), 0);
                    }
                    break;
                case "MoveRight":
                    FunctionsUtils.AddItemsToAnotherListBoxAndDeleteIt(lbCategoryLeft, lbCategoryRight, false);
                    break;
                case "MoveLeft":
                    FunctionsUtils.AddItemsToAnotherListBoxAndDeleteIt(lbCategoryRight, lbCategoryLeft, false);
                    break;
                case "MoveAllRight":
                    FunctionsUtils.AddItemsToAnotherListBoxAndDeleteIt(lbCategoryLeft, lbCategoryRight, true);
                    break;
                case "MoveAllLeft":
                    FunctionsUtils.AddItemsToAnotherListBoxAndDeleteIt(lbCategoryRight, lbCategoryLeft, true);
                    break;
                case "DeleteImages":
                    //ltPicturesError.Text = lstImages.Value;
                    this.DeleteImages(lstImages.Value, this.ProductISN);
                    break;
                case "SetAvatar":
                    this.SetAvatar(SelectForAvatar.Value, this.ProductISN);
                    break;
                case "SaveSpecification":
                    //this.UpdateSpecification(this.ProductISN, Editor1.ContentHTML);
                    this.UpdateSpecification(this.ProductISN, txtEditor.Text);
                    //ltError.Text = txtEditor.Text;
                    break;
            }
        }

        private bool CheckData()
        {
            ltProductInfoError.Text = string.Empty;
            ltUpdateSuccess.Text = string.Empty;
            bool bResult = true;

            if (txtProductName.Text.Trim().Length == 0)
            {
                FunctionsUtils.ShowSmallError(ltProductNameErr, FunctionsUtils.Msg["frm_Required"]);
                bResult = false;
            }

            if (txtPrice.Text.Trim().Length == 0)
            {
                FunctionsUtils.ShowSmallError(ltPriceErr, FunctionsUtils.Msg["frm_Required"]);
                bResult = false;
            }
            else
            {
                if (ValidateUtils.isPosNumber(txtPrice.Text.Trim(), NumberType.Decimal, false) == false)
                {
                    FunctionsUtils.ShowSmallError(ltPriceErr, string.Format(FunctionsUtils.Msg["frm_NumberMin"], "", "0"));
                    bResult = false;
                }
            }

            if (txtOnhandQty.Text.Trim().Length == 0)
            {
                FunctionsUtils.ShowSmallError(ltOnhandQtyErr, FunctionsUtils.Msg["frm_Required"]);
                bResult = false;
            }
            else
            {
                if (ValidateUtils.isNumber(txtOnhandQty.Text.Trim(), NumberType.Integer) == false)
                {
                    FunctionsUtils.ShowSmallError(ltOnhandQtyErr, FunctionsUtils.Msg["frm_Format"]);
                    bResult = false;
                }
            }

            if (lbCategoryRight.Items.Count == 0)
            {
                ltProductInfoError.Text = string.Format(FunctionsUtils.Msg["sel_Item"], "Category");
                bResult = false;
            }

            return bResult;
        }

        private void SaveProduct(int productISN, string proName, int proStatus, decimal proPrice, decimal proOnHandQty, string lstCategoryISN, string proComments, int updateBy)
        {
            ltProductNameErr.Text = string.Empty;
            ltPriceErr.Text = string.Empty;
            ltOnhandQtyErr.Text = string.Empty;
            ltProductInfoError.Text = string.Empty;
            ltUpdateSuccess.Text = string.Empty;

            try
            {
                int iResult = (int)FunctionsUtils.Database.ExecuteStoredProcReturnObject("xp_productinfo_insupd",
                    new string[] { "ProductISN", "proName", "proStatus", "proPrice", "proOnHandQty", "proComment", "lstCategoryISN", "updatedBy" },
                    new object[] { productISN, FunctionsUtils.DoubleSingleQuote(proName), proStatus, proPrice, proOnHandQty, FunctionsUtils.DoubleSingleQuote(proComments), lstCategoryISN, updateBy });

                if (iResult < 0)
                {
                    switch (iResult)
                    {
                        case -2: //proName exist
                            ltError.Text = string.Format(FunctionsUtils.Msg["frm_Exist"], "Category");
                            break;
                    }
                }
                else
                {
                    ltProductName.Text = txtProductName.Text;
                    ltUpdateSuccess.Text = FunctionsUtils.Msg["SaveChangesSuccess"];
                }
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (SaveProduct): {0} {1}", ex, ex.StackTrace);
            }
        }

        private void GetImagesOfProduct(int productISN)
        {
            try
            {
                DataSet ds = FunctionsUtils.Database.ExecuteQuery("Select * From ProPicture Where ProductISN = " + productISN.ToString());
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    rpImages.DataSource = ds.Tables[0];
                }
                else
                {
                    rpImages.DataSource = null;
                }
                rpImages.DataBind();
            }
            catch(Exception ex)
            {
                ltPicturesError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (GetImageOfProduct): {0} {1}", ex, ex.StackTrace);
            }
        }

        //public string GetImageUrl(object productISN, object imageFileName)
        //{
        //    return string.Format("{0}{1}/{2}", FunctionsUtils.GetConfigValue("ProductImageUrl"), productISN, imageFileName);
        //}

        private void DeleteImages(string lstImages, int productISN)
        {
            try
            {
                string productImageDir = Path.Combine(FunctionsUtils.GetConfigValue("ProductImageDir"), this.ProductISN.ToString());
                string[] arrPictureISN = lstImages.Split(',');
                string imageFileName = string.Empty;
                for (int i = 0; i < arrPictureISN.Length; i++)
                {
                    imageFileName = FunctionsUtils.Database.ExecuteQuery("Select [FileName] From ProPicture Where PictureISN = " + arrPictureISN[i]).Tables[0].Rows[0]["FileName"].ToString();
                    //delete file images
                    File.Delete(Path.Combine(productImageDir, imageFileName));
                    //delete in database
                    FunctionsUtils.Database.ExecuteQuery(string.Format("Delete ProPicture Where PictureISN = {0}", arrPictureISN[i]));                
                }
                //reload data
                this.GetImagesOfProduct(productISN);
            }
            catch (Exception ex)
            {
                ltPicturesError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (DeleteImages): {0} {1}", ex, ex.StackTrace);
            }
        }

        private void SetAvatar(string pictureISN, int productISN)
        {
            try
            {
                FunctionsUtils.Database.ExecuteStoredProc("xp_propicture_setavatar", new string[] { "PictureISN" }, new object[] { pictureISN });

                this.GetImagesOfProduct(productISN);

                ltUpdateSuccess.Text = FunctionsUtils.Msg["SaveChangesSuccess"];
            }
            catch (Exception ex)
            {
                ltPicturesError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (SetAvatar): {0} {1}", ex, ex.StackTrace);
            }
        }

        public string GetAvartarCss(object isAvatar)
        {
            int i = FunctionsUtils.ConvertToInt(isAvatar, 0);
            if (i == 1)
                return string.Format("class='selectAvatar'");
            return string.Empty;
        }

        public void UpdateSpecification(int productISN, string proDescription)
        {
            //[xp_product_spec_upd](@ProductISN int, @Desc nvarchar(max))
            ltSpecificationError.Text = string.Empty;
            try
            {
                FunctionsUtils.Database.ExecuteStoredProcReturnObject("xp_product_spec_upd", new string[] { "ProductISN", "Desc" }, new object[] { productISN, FunctionsUtils.DoubleSingleQuote(proDescription) });

                //Editor1.ContentHTML = proDescription;
                ltUpdateSuccess.Text = FunctionsUtils.Msg["SaveChangesSuccess"];
            }
            catch (Exception ex)
            {
                ltSpecificationError.Text = ex.Message;
                log.WriteLog("Error in ProductDetail (UpdateSpecification): {0} {1}", ex, ex.StackTrace);
            }
        }

        //public void Editor1_Save(object sender, EditorSaveEventArgs args)
        //{
        //    this.UpdateSpecification(this.ProductISN, args.Content);            
        //}
    }
}
